import DeliverApi from '../../../common/api/breedsales/deliverbills.api.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { Select2Page } from "../../../common/serve-request.js";
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
(function (window, document, $) {
    let _vm, savetype, getEntryInfo = []
    $(function () {
        _vm = new Vue({
            el: "#saleordersentry-form",
            data() {
                return {
                    entries: [{
                        "seq": "",
                        "count": 1,
                        "reasion": "",
                        "reasionName": ""
                    }],
                    uploadCount: 0
                }
            },
            methods: {
                submit() {
                    if (!Utils.IsNotNull(_vm.entries[0].reasion)) {
                        return $.toptip(`请选择死亡原因!`, 'warning');
                    }
                    if (!Utils.IsNotNull(_vm.entries[0].count)) {
                        return $.toptip(`请输入死亡数量!`, 'warning');
                    }
                    if (!(/(^[1-9]\d*$)/.test(_vm.entries[0].count))) {
                        return $.toptip(`死亡数量必须为大于0的整数!`, 'warning');
                    }
                    savetips({ ..._vm.entries[0] })
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                if (params.isEdit == 'true') {
                    document.title = '死亡记录分录 - 编辑'
                }
            },
        });

        _initCommand();
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    // 初始化数据
    const _initCommand = async () => {
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo")) || []
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let seq = getUrlKey('index')
        // 编辑时赋值
        if (isEdit) {
            let datas = getEntryInfo.find(item => item.seq == seq)
            _vm.entries[0].reasion = datas?.reasion
            _vm.entries[0].reasionName = datas?.reasionName
            _vm.entries[0].seq = datas?.seq
            _vm.entries[0].count = datas?.count
        }
        //死亡原因
        let type = await requestDict(DictionaryType.FAT_PIG_DEATH_CAUSE)
        let pigList = type.data
        $('#PigLetReason').empty().select2({
            placeholder: '请选死亡原因...', //默认文字提示
            language: "zh-CN", //汉化
            allowClear: true, //允许清空
            multiple: false,
            data: pigList.map(item => {
                return {
                    id: item.value,
                    text: item.displayName,
                }
            }),
        });
        $(`#PigLetReason`).setSelectValue();
        if (Utils.IsNotNull(_vm.entries[0].reasion)) {
            $(`#PigLetReason`).setSelectValue(_vm.entries[0].reasion, _vm.entries[0].reasionName);
        }

        $('#PigLetReason').on("select2:select", async function () {
            _vm.entries[0].reasion = $('#PigLetReason').select2('data')[0]?.id
            _vm.entries[0].reasionName = $('#PigLetReason').select2('data')[0]?.text
        })
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../deathbills/adddeathbills.html?v=${Utils.GetTime()}`;
        });
    }

    // 保存提示
    const savetips = (data) => {
        let saveEntry
        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
            savetype = '修改'
            saveEntry = getUrlKey("operaEntryId")
        }
        else {
            savetype = '保存'
            saveEntry = getUrlKey('nextEntryId')
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))
                        // 新增
                        if (Utils.IsNotNull(getEntryInfo) && isEdit == false) {
                            getEntryInfo.push(data)
                        } else if (Utils.IsNotNull(getEntryInfo) && isEdit) {
                            // 编辑
                            getEntryInfo[seq] = data
                        } else {
                            getEntryInfo.push(data)
                        }
                        getEntryInfo.map((item, index) => {
                            item.seq = index
                        })
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getEntryInfo", getEntryInfo))
                        location.href = `./adddeathbills.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

})(window, document, jQuery)